<?php

/**
 * Отображение документа типа "квест"
 *
 */
class Action_Quest_ShowQuest extends RL_Handler
{
	/**
	 *
	 * @var Model_Quest
	 */
	private $model;
	/**
	 *
	 * @var AggregatedModel_Feed_ReaderItems
	 */
	private $rModel;
	private $oQuest;
	private $view;

	private $votingId;
	private $sortBy;
	private $isFinioshOnly;

	public function init()
	{
		session_start();
		$questId = $this->params['id_quest'];
		/*модельки*/
		$this->rh->UseClass('Model_Item');
		$this->model = $this->ctx->mm->getModel("Quest");
		$this->oQuest = $this->model->getItem($questId);
		/*если квест не опубликован - перейти к его редактированию*/
		$this->rh->useClass("RL_URLGenerator");
		if(!$this->oQuest->data['is_published']) {
			$this->rh->redirect($this->getEditUrl());
		}
		/*параметры поиска*/
		$this->votingId = intval($this->rh->GET['v']);
		$this->sortBy = intval($this->rh->GET['s']);
		$this->isFinioshOnly = intval($this->rh->GET['f']);
		/*ридер документов*/
		$this->rh->UseClass("AggregatedModel_Feed_FeedInterface");
		$this->rModel = $this->ctx->mm->getModel("Feed_ReaderItems", "a");
		$this->rModel->rh = $this->rh;
		$this->rModel->setModelParams("no_pager", true);
		/* секции */
		$this->module->aa->getInfo();
		$this->m_tdi = $this->ctx->mm->getModel("Tdi", "m");
		$tdi_oids = array();
		foreach ($this->aa->acl_data['tdi_list'] as $tdi) $tdi_oids[] = $tdi['id_object'];
		$this->sections = $this->m_tdi->getSections($tdi_oids);
	}

	private function getEditUrl()
	{
		$ug = new RL_URLGenerator($this->rh->router->getRule("edit_quest")); //
		$ug->setRouter($this->rh->router);
		$ug->setParams(array(
			"community_url"=>$this->params['community_url'],
			"quest_id"=>$this->oQuest->id,
			"quest_step"=>0,
			)
		);
		return $ug->generateUrl();
	}

	private function getAdminUrl()
	{
		$ug = new RL_URLGenerator($this->rh->router->getRule("admin_quest")); //
		$ug->setRouter($this->rh->router);
		$ug->setParams(array(
			"community_url"=>$this->params['community_url'],
			"quest_id"=>$this->oQuest->id,
			)
		);
		return $ug->generateUrl();
	}

	public function process()
	{
 		// -- old theme HACK : 2008-05-21 : lucky -- {{{
		$community_skin = 'platonica';
		$tpl = $this->ctx->tpl;
		$community_model = $this->ctx->mm->getModel("Community");
		$community_model->setDefaultSkin($community_skin);
		$tpl->setSkin($community_skin);
		$views_php = $tpl->findFile('', 'views', $tpl->_skin, 'php');
		unset ($config);
		include $views_php; // got $config
		$this->ctx->rh->views->setViewConfig($config);
		// -- old theme HACK : 2008-05-21 : lucky -- }}}

		$this->view = $this->rh->views->findByName('show_quest');
		$this->view->data = $this->module->aa->template_data;

		$this->view->data['quest'] = $this->oQuest->data;
		$this->view->data['quest']['id'] = $this->oQuest->id;
		//если пользователь обладает правами гивера - вывести ссылки на модерирование и редактирование
		$roles = $this->model->getUserRole($this->oQuest);
		if ($roles[Model_Quest::ROLE_GIVER]) {
			$this->view->data['admin_link'] = $this->getAdminUrl();
			$this->view->data['edit_link'] = $this->getEditUrl();
		}
		$this->showTabPanel();

		$this->showSearchResults();

		$this->rh->response->setContent( $this->view );

		// -- touch visitor stat -- {{{
		// visit  tdi
		$this->ctx->mm->getModel("Visitable", "m")->getVisitable('Item')->setWhat($this->oQuest->id)->visit();
		//
		// -- touch visitor stat -- }}}

	}

	private function showFeedUrl()
	{
		$ug = new RL_URLGenerator($this->rh->router->getRule("showfeed"));
		$ug->setRouter($this->rh->router);
		$ug->setParams(array(
			"community_url"=>$this->params['community_url'],
			)
		);
		$this->view->data['feed_url'] = $ug->generateUrl();
	}


	private function votingForTempl($voting)
	{
		$id = $voting['vote_id'];

		return array(
			'name'  => $voting['name'],
			'url'   => $this->genUrl($id),
			'cur'   => $this->votingId==$id,
		);
	}

	private function showTabPanel()
	{
		//номинации
		$votings = $this->model->getVotes($this->oQuest);
		$vs = array(
			0=>$this->votingForTempl(array('name'=>'Все номинации','vote_id'=>0))
		);
		$count = count($votings);
		$curVt = null;
		for($i=1; $i<=$count; $i++){
			$vt = $this->votingForTempl($votings[$i-1]);
			if($vt['cur'])
				$curVt = $i;
			$vs[$i] = $vt;
		}
		//номинации разбиваем на два массива $vsa и $vsh - активные и скрытые
		if($count <= 3) {
			//если три и менее номинации - прятать ничего не надо
			$vsa = $vs;
		} else {
			//определим какие отображать
			$sessKey = 'showquest_at_'.$this->oQuest->id;
			if(!is_array($_SESSION[$sessKey])) {
				//впервые на странице - показать первые две
				$_SESSION[$sessKey] = array(1,2);
			}
			if($curVt !== null && !in_array($curVt, $_SESSION[$sessKey])) {
				//выбрана неактивная ссылка, показать её
				$_SESSION[$sessKey][1] = $_SESSION[$sessKey][0];
				$_SESSION[$sessKey][0] = $curVt;
			}
			//показываем активные
			$vsa = array(
				$vs[0],
				$vs[$_SESSION[$sessKey][0]],
				$vs[$_SESSION[$sessKey][1]],
			);
			//показывем скрытые
			$vsh = array();
			for($i=1; $i<=$count; $i++){
				if(!in_array($i, $_SESSION[$sessKey])) {
					$vsh[] = $vs[$i];
				}
			}
		}
		$this->view->data['votings'] = $vsa;
		$this->view->data['votings_hide'] = $vsh;

		//сортировка
		$this->view->data['sort_by'] = $this->sortBy;
		$this->view->data['sort_url'] = $this->genUrl(null,$this->sortBy?0:1);
		//финалисты
		$this->view->data['is_finish'] = $this->isFinioshOnly;
		$this->view->data['finish_url'] = $this->genUrl(null,null,$this->isFinioshOnly?0:1);
	}

	private function processItem($it)
	{
		$this->rModel->setModelParams("item_oid", $it['oid']);
		$this->rModel->doStuff();
		$oDoc = $this->model->getItem($it['oid']);
		$item = $this->rModel->getItems();
		$item = $item[0];
		$item['actions'] = $this->model->getDocumentActions($this->oQuest, $oDoc);

		//$item['balls'] = intval($it['balls']);
		$item['voters'] = $this->model->getVotersCount($this->oQuest, $oDoc);
		$item['action_url'] = $this->model->getDocActionUrl($this->oQuest->id, $it['oid']);
		//кнопки голосования  иметь состояния:
		// в финале
		if($it['state'] == Model_Quest::STATE_INFINAL) {
			$item['btns']['f'] = "f";
		}
		// голосовал или не голосовал
		$vote_state = $item['actions']['vote_ok'] ? "n" : "v";
		$item['btns'][$vote_state] = $vote_state;

		//а теперь код 1 в 1 передранный с ShowFeed.php
		$item['section'] = $this->sections[ $item['post']['tdi_oid'] ];
		$item['acl'] = $this->module->aa->getAcl( $item['post']['oid'] );

		if ($item['post']['type'] == 'fvote') {
			// установить bool $item['voted'] если текущий пользователь голосовал
			$vm = $this->ctx->mm->getModel("Vote", "m");
			$aa = $this->aa;
			$item['already_voted'] = $vm->checkUserVote($item['post']['oid'], $aa->acl_data['user_id']);

			// создать ссылку на голосоватор за данный итем
			$ug = new RL_URLGenerator($this->rh->router->getRule("vote_manager")); //
			$ug->setRouter($this->rh->router);
			$ug->setParams(array(
				"community_url"=>$this->params['community_url'],
				"id_item"=>$item['post']['oid'],
			)
		);
			$item['vote_url'] = $ug->generateUrl();
			unset($ug);

			if ($item['post']['posted_by_id'] == $this->aa->acl_data['user_id']) {
				$item['can_close'] = 1;
			}

			$item['can_vote'] = (isset($this->aa->acl_data['user_id'])) ? true : false;
		}
		return $item;
	}

	private function showSearchResults()
	{
		$params = array(
			'sort_by'   => $this->sortBy?"date":"balls",
			'in_final'  => $this->isFinioshOnly?true:null,
			'voting_id' => $this->votingId==0?null:$this->votingId,
		);

		$items = $this->model->getQuestDocuments($this->oQuest, $params);

		$docs = array();
		foreach($items as $item) {
			$docs[] = $this->processItem($item);
		}
		$this->view->data['search_items'] = $docs;
		$this->showFeedUrl();
		//найдём и отобразим количество финалистов/всех
		$params['in_final'] = $params['in_final']?null:true;
		$otherCount = $this->model->getQuestDocumentsCount($this->oQuest, $params);
		$this->view->data['final_count'] = $otherCount;
	}

	private function genUrl($votingId=null,$sortBy=null,$isFinishOnly=null)
	{
		$gets = array();

		$gets[] = "v=".($votingId===null?$this->votingId:$votingId);
		$gets[] = "s=".($sortBy===null?$this->sortBy:$sortBy);
		$gets[] = "f=".($isFinishOnly===null?$this->isFinioshOnly:$isFinishOnly);

		return "?".implode("&", $gets);
	}
}
